package com.example.dmy.bootoauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @Author: daimengying
 * @Date: 2019/1/5 09:34
 * @Description:资源服务器配置
 */
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public MyUserDetailsService myUserDetailsService(){
        return new MyUserDetailsService();
    }
    @Autowired
    DataSource dataSource;
//    @Autowired
//    private MyFilterSecurityInterceptor myFilterSecurityInterceptor;

    /**
     * 配置.忽略的静态文件，不加的话，登录之前页面的css,js不能正常使用，得登录之后才能正常.
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略URL
        web.ignoring().antMatchers("/**/*.js", "/lang/*.json",
                "/**/*.css", "/**/*.js", "/**/*.map", "/**/*.html",
                "/**/*.png");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        重写默认的用户查询功能
//        auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(
//                "select username,password,enabled from g_oauth_user where username=?")
//                .authoritiesByUsernameQuery("select username, ‘ROLE_USER‘ from Spitter where username=?");
//        auth.userDetailsService(userDetailsService);
        auth.userDetailsService(myUserDetailsService()).passwordEncoder(passwordEncoder());
    }

    /**
     * 重写authenticationManagerBean方法,防止注入失败
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.requestMatchers().antMatchers("/api/**")
//                .and()
//                .authorizeRequests()
//                .antMatchers("/api/**").authenticated();
        http.authorizeRequests()
                .antMatchers("/**/*.js",
                        "/**/*.css","/oauth/**","/hello"
                ).permitAll()
//                .antMatchers("/hello").access("hasRole('USER') and hasRole('ADMIN')")
                //其他的请求都必须要有权限认证
                .anyRequest()
                .authenticated()
                .and()
                .formLogin() //允许用户进行基于表单的认证
                .and()
                // 暂时禁用CSRF，否则无法提交登录表单
                .csrf().disable();
//        http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
